package com.geovis.boot.service.config.web;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class GbInterceptor extends HandlerInterceptorAdapter {
    private String prefix = "WEB_INTERCEPTO";
    /**
     * This implementation always returns {@code true}.
     *
     * @param request
     * @param response
     * @param handler
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("{} request url: {}", prefix, request.getRequestURL());
        Map<String, String> headerMap = new HashMap<>();
        Enumeration<String> headers = request.getHeaderNames();
        while(headers.hasMoreElements()){
            String header = headers.nextElement();
            headerMap.put(header, request.getHeader(header));
        }
        log.info("{} request headers: {}", prefix, JSONUtil.toJsonStr(headerMap));
        log.info("{} request method: {}", prefix, request.getMethod());
        log.info("{} request url: {}", prefix, request.getRequestURL().toString());
        log.info("{} request parameters: {}", prefix, JSONUtil.toJsonStr(getParameterMap(request)));
        log.info("{} request ip: {}", prefix, request.getRemoteAddr());
        return super.preHandle(request, response, handler);
    }

    /**
     * This implementation is empty.
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("{} response : {}", prefix, JSONUtil.toJsonStr(response));
        super.postHandle(request, response, handler, modelAndView);
    }

    /**
     * This implementation is empty.
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }

    private Map<String, String> getParameterMap(HttpServletRequest request){
        Enumeration<String> paramNames = request.getParameterNames();
        Map<String, String> paramMap = new HashMap<>();
        while (paramNames.hasMoreElements()){
            String param = paramNames.nextElement();
            paramMap.put(param, request.getParameter(param));
        }
        return paramMap;
    }
}
